/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月5日 下午10:30:14
 */

package datang.dtdb.scripting;

import java.util.Objects;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import datang.dtdb.builder.BaseBuilder;
import datang.dtdb.mapping.SqlSource;
import datang.dtdb.parsing.XPathParser;
import datang.dtdb.session.Configuration;

public class XMLScriptBuilder extends BaseBuilder {

	/**
	 * 当前CURD标签中的一个
	 */
	private Node statementNode;

	/**
	 * 是否动态
	 */
	private boolean isDynamic;

	public XMLScriptBuilder(Configuration configuration, Node statementNode) {
		super(configuration);
		this.statementNode = statementNode;
	}

	public SqlSource parseScriptNode() {
		MixedSqlNode rootSqlNode = parseDynamicTags(statementNode);
		SqlSource sqlSource;
		if (isDynamic) {
			sqlSource = new DynamicSqlSource(configuration,rootSqlNode);
		} else {
			sqlSource = new RawSqlSource(configuration,rootSqlNode);
		}
		return sqlSource;
	}

	protected MixedSqlNode parseDynamicTags(Node node) {
		NodeList childs = XPathParser.listEle(node);
		MixedSqlNode mixedSqlNode = new MixedSqlNode();
		for (int i = 0; i < childs.getLength(); i++) {
			Node child = childs.item(i);
			short nodeType = child.getNodeType();
			if (nodeType == Node.TEXT_NODE) {
				String data = child.getTextContent().trim();
				if (!data.equals("")) {
					TextSqlNode textSqlNode = new TextSqlNode(data);
					if (textSqlNode.isDynamic()) {
						mixedSqlNode.addSqlNode(textSqlNode);
						isDynamic = true;
					} else {
						mixedSqlNode.addSqlNode(new StaticSqlNode(data));
					}
				}
			} else if (nodeType == Node.ELEMENT_NODE) {
				isDynamic = true;
			}
		}
		return mixedSqlNode;
	}
	

}
